﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VoiceAd.Models;
using VoiceAd.DAL;
using System.IO;
using System.Web.Security;
using System.Text;
using VoiceAd.Common;

namespace VoiceAd.Controllers
{
    public class CustomerController : Controller
    {
        private IlogRepository logRepository = new LogRepository(new dbVoiceAdDataContext());
        private IAreaRepository areaRepository = new AreaRepository(new dbVoiceAdDataContext());
        private IProvinceRepository provinceRepository = new ProvinceRepository(new dbVoiceAdDataContext());
        private IDistrictRepository districtRepository = new DistrictRepository(new dbVoiceAdDataContext());
        private ICampaignRepository campaignRepository = new CampaignRepository(new dbVoiceAdDataContext());
        private IBookingRepository bookingRepository = new BookingRepository(new dbVoiceAdDataContext());
        private IBlockRepository blockingRepository = new BlockRepository(new dbVoiceAdDataContext());
        private ICustomerRepository customerRepository = new CustomerRepository(new dbVoiceAdDataContext());
        private IStationRepository stationRepository = new StationRepository(new dbVoiceAdDataContext());
        private IMonitorRepository monitorRepository = new MonitorRepository(new dbVoiceAdDataContext());
        private IServicesRepository servicesRepository = new ServicesRepository(new dbVoiceAdDataContext());
        private IAudioCampRepository audioCampRepository = new AudioCampRepository(new dbVoiceAdDataContext());
        private ISendMailGroupRepository sendMailGroupRepository = new SendMailGroupRepository(new dbVoiceAdDataContext());

        [Authorize(Roles = "Customer")]
        public ActionResult Index()
        {
            ViewBag.lstArea = areaRepository.GetListAreas();
            var lstActive = campaignRepository.GetListActiveCampaignsbyCusId();
            ViewBag.lstActive = lstActive;

            tblCampaign tbl = lstActive.ToList().FirstOrDefault();
            if (tbl != null)
            {
                ViewBag.lstAudio = audioCampRepository.GetListAudioCampsbyCampId(tbl.Id);
            }

            ViewBag.lstCampaign = campaignRepository.GetListCampaignsbyCusId();
            subMenuServices();
            return View();
        }

        [Common.MyFunction.HttpParamAction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(string[] chkArea)
        {
            List<tblDistrict> lst = new List<tblDistrict>();
            if (chkArea != null && chkArea.Length > 0)
            {
                for (int i = 0; i < chkArea.Length; i++)
                {
                    string idArea = chkArea[i];
                    lst.AddRange(districtRepository.GetListDistricts(int.Parse(idArea)));
                }
                ViewBag.lstProvince = lst;
            }
            GetListCustomer();
            subMenuServices();
            return View("regArea");
        }

        [Common.MyFunction.HttpParamAction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Search(string txtSearch)
        {
            ViewBag.lstCampaign = campaignRepository.GetListCampaignsbyCusId(txtSearch);
            subMenuServices();
            return View("lstCampaign");
        }

        public void GetListCustomer(object obj = null)
        {
            var lst = customerRepository.GetListCustomers().ToList();

            tblCustomer tbl = new tblCustomer { Id = -1, UserName = "Chọn khách hàng" };
            lst.Insert(0, tbl);
            ViewBag.lstCustomer = new SelectList(lst, "Id", "UserName", obj);
        }

        [HttpPost]
        public ActionResult RegArea(int CustomerId, string txtTitle, string txtFDate, string txtTDate, string txtUrl, string[] chkDistrict, string[] txtNam, string[] txtThang, string[] arrDay, string txtSoNgay, string txtDonGia, string txtDiscount)
        {
            tblCampaign objCamp = new tblCampaign();
            objCamp.Approve = false;
            objCamp.BeginDay = DateTime.Parse(txtFDate);
            objCamp.Title = txtTitle;

            if (Roles.IsUserInRole("admin"))
            {
                objCamp.CustomerId = CustomerId;
            }
            else
            {
                objCamp.CustomerId = customerRepository.GetCustomerByName().Id;
            }

            objCamp.EndDay = DateTime.Parse(txtTDate);

            if (!string.IsNullOrEmpty(txtSoNgay))
                objCamp.SoNgay = short.Parse(txtSoNgay);

            if (!string.IsNullOrEmpty(txtDiscount))
                objCamp.ChietKhau = int.Parse(txtDiscount);
            else
                objCamp.ChietKhau = 0;

            if (!string.IsNullOrEmpty(txtDonGia))
            {
                int intDonGia = int.Parse(txtDonGia);
                intDonGia -= intDonGia * objCamp.ChietKhau.Value / 100;
                objCamp.DonGia = intDonGia;
            }
            else
                objCamp.DonGia = 0;

            campaignRepository.InsCampaign(objCamp);

            if (!string.IsNullOrEmpty(txtUrl))
            {
                int intSTT = 1;
                foreach (string str in txtUrl.Split(';'))
                {
                    if (!string.IsNullOrEmpty(str))
                    {
                        tblAudioCamp objAudio = new tblAudioCamp();
                        objAudio.CampaignId = objCamp.Id;
                        string strNews = Common.UrlEncode.ToFriendlyUrl(txtTitle) + "-0" + intSTT.ToString() + "-" + MyFunction.FormatString(txtNam.First(), txtThang.First());
                        objAudio.UrlAudio = UpdateFile(str, strNews);
                        audioCampRepository.InsAudioCamp(objAudio);
                        intSTT++;
                    }
                }
            }

            tblStation objStation = new tblStation();
            int groupNum = 1;
            int stt = 0;

            int intTime = txtNam.Length;
            for (int i = 0; i < chkDistrict.Length; i++)
            {
                objStation = stationRepository.GetStationByDistrictId(int.Parse(chkDistrict[i]));
                if (objStation != null)
                {
                    //Insert Data to tblSendMailGroup
                    string[] words = objStation.Email.Split(';');
                    foreach (string word in words)
                    {
                        if (stt > 91)
                        {
                            groupNum++;
                            stt = 0;
                        }
                        tblSendMailGroup objSendMailGroup = new tblSendMailGroup();
                        objSendMailGroup.CampaignId = objCamp.Id;
                        objSendMailGroup.GroupNum = groupNum;
                        objSendMailGroup.Email = word;
                        objSendMailGroup.Status = 0;
                        objSendMailGroup.StationId = objStation.Id;
                        sendMailGroupRepository.Ins(objSendMailGroup);
                        stt++;
                    }

                    tblBooking objBook = new tblBooking();
                    objBook.CampaignId = objCamp.Id;
                    objBook.StationId = objStation.Id;
                    objBook.Title = objCamp.Title + " - " + objStation.StationName;

                    bookingRepository.InsBooking(objBook);

                    for (int j = 0; j < intTime; j++)
                    {
                        if (!string.IsNullOrEmpty(txtNam[j]))
                        {
                            tblBlock objBlock = new tblBlock();
                            objBlock.BookingId = objBook.Id;
                            objBlock.DayBook = arrDay[j];
                            objBlock.MonthBook = int.Parse(txtThang[j]);
                            objBlock.YearBook = int.Parse(txtNam[j]);
                            objBlock.IsApprove = false;

                            if (objStation.UnitPrice != null)
                                objBlock.MonthPrice = (int)objStation.UnitPrice;
                            else
                                objBlock.MonthPrice = 0;

                            blockingRepository.InsBlock(objBlock);
                        }
                    }
                }
            }
            return Redirect("index");
        }

        public string UploadAvatar(IEnumerable<HttpPostedFileBase> fileData)
        {
            string strName = string.Empty;
            string strPath = string.Empty;
            string strResult = string.Empty;

            foreach (var f in fileData)
            {
                strName = Guid.NewGuid().ToString() + Path.GetExtension(f.FileName);
                strPath = Path.Combine(Server.MapPath("~/uploads"), strName);
                f.SaveAs(strPath);
                strResult += strName + ";";
            }

            return strResult;
        }

        public ActionResult Campaign(int id)
        {
            tblCampaign tbl = campaignRepository.GetCampaignById(id);
            ViewBag.lstAudio = audioCampRepository.GetListAudioCampsbyCampId(tbl.Id);

            tblCustomer tblCus = customerRepository.GetCustomerByName();

            ViewBag.lstDistrictCampaign = campaignRepository.CampaignGetListDistrict(tbl.Id, tblCus.Id);

            subMenuServices();
            return View(tbl);
        }

        public ActionResult CampaignDetail(int id)
        {
            tblBooking tblbk = bookingRepository.GetBookingById(id);
            tblCampaign tblcb = campaignRepository.GetCampaignById(Convert.ToInt32(tblbk.CampaignId));
            ViewBag.Campaign = tblcb.Title;

            tblStation tblst = stationRepository.GetStationById(Convert.ToInt32(tblbk.StationId));
            tblDistrict tbldt = districtRepository.GetDistrictById(Convert.ToInt32(tblst.DistrictId));

            ViewBag.DistrictName = tbldt.DistrictName + " _ " + tbldt.tblProvince.ProvinceName;

            ViewBag.lstMonitor = monitorRepository.GetListMonitorsByBookingId(id);
            return View();
        }

        public void subMenuServices()
        {
            StringBuilder str = new StringBuilder();
            str = str.AppendLine("<ul>");
            IEnumerable<tblServices> lstServices = servicesRepository.GetListService();
            foreach (tblServices tbl in lstServices)
            {
                string lUrl = Url.Content("~/service-" + VoiceAd.Common.UrlEncode.ToFriendlyUrl(tbl.Title_Vn) + "-" + tbl.Id.ToString() + ".html");
                str.AppendLine("<li><a href=" + lUrl + ">" + tbl.Title_Vn + "</a></li>");
            }
            str = str.AppendLine("</ul>");
            ViewBag.lstSubMenu = str.ToString();
        }

        protected override void Dispose(bool disposing)
        {
            areaRepository.Dispose();
            provinceRepository.Dispose();
            districtRepository.Dispose();
            campaignRepository.Dispose();
            blockingRepository.Dispose();
            bookingRepository.Dispose();
            customerRepository.Dispose();
            stationRepository.Dispose();
            monitorRepository.Dispose();
            servicesRepository.Dispose();
            audioCampRepository.Dispose();
            sendMailGroupRepository.Dispose();
            logRepository.Dispose();
        }

        public string UpdateFile(string strName, string strTitle)
        {
            string strPath = Server.MapPath("~/uploads");

            string strFile = Path.Combine(Server.MapPath("~/uploads"), strName);
            string strExt = Path.GetExtension(strFile);
            string strFolder = Path.Combine(strPath, "Customer");

            if (!Directory.Exists(strFolder))
            {
                Directory.CreateDirectory(strFolder);
            }

            strFolder = Path.Combine(strFolder, strTitle + strExt);

            System.IO.File.Copy(strFile, strFolder, true);
            System.IO.File.Delete(strFile);

            return (strTitle + strExt);
        }


        public JsonResult updateVoice(string fileVoice, int audioCampID)
        {
            tblAudioCamp objAudio = audioCampRepository.GetAudioCampById(audioCampID);
            if (!string.IsNullOrEmpty(fileVoice))
            {
                int intSTT = 1;
                foreach (string str in fileVoice.Split(';'))
                {
                    if (!string.IsNullOrEmpty(str))
                    {
                        string strNews = Common.UrlEncode.ToFriendlyUrl(fileVoice) + "-0" + intSTT.ToString();
                        objAudio.UrlAudio = UpdateFile(str, strNews);
                        audioCampRepository.UpdAudioCamp(objAudio);
                        intSTT++;
                    }
                }
            }

            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = "Update file voice";
            tbllog.Description = "Chiến dịch: " + objAudio.tblCampaign.Title;
            logRepository.InsLog(tbllog);

            return Json(objAudio.UrlAudio, JsonRequestBehavior.AllowGet);
        }

        public ActionResult PrintExcel(int Id)
        {
            double intDanSo = 0;
            Int64 intSoXa = 0;
            Int64 intTanSuat = 0;
            double intTongLuotNghe = 0;
            double intDoReach = 0;
            double intTongCpm = 0;
            double intTongDonGia = 0;

            Response.ClearContent();

            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "List.xls"));
            Response.Write("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            Response.Write("<head>");
            Response.Write("<style>table{border-collapse: collapse;border-spacing: 0;background-color: transparent; color: #333333}");
            Response.Write("table, td, th {border:1px solid black; padding:10px}</style>");
            Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
            Response.ContentType = "application/ms-excel";

            Response.Write("<table>");
            Response.Write("<tr>");
            Response.Write("<td>STT</td>");
            Response.Write("<td>Vùng</td>");
            Response.Write("<td>Tỉnh</td>");
            Response.Write("<td>Huyện</td>");
            Response.Write("<td>Số xã/Thị trấn</td>");
            Response.Write("<td>Dân số</td>");
            Response.Write("<td>Tần suất phát sóng</td>");
            Response.Write("<td>Tổng số lượt nghe</td>");
            Response.Write("<td>Độ reach 70%</td>");
            Response.Write("<td>CPM (USD)</td>");
            Response.Write("<td>Buổi sáng</td>");
            Response.Write("<td>Trưa</td>");
            Response.Write("<td>Chiều</td>");
            Response.Write("<td>Đơn giá</td>");
            Response.Write("<td>Số ngày phát</td>");
            Response.Write("<td>Giảm giá</td>");
            Response.Write("<td>Thành tiền</td>");

            List<tblListMonth> lstMonth = campaignRepository.tblCampaignGetListMonth(Id).ToList();
            foreach (tblListMonth tbl in lstMonth)
            {
                int intMonth = DateTime.DaysInMonth(tbl.YearBook, tbl.MonthBook);
                Response.Write("<td style='text-align:center' colspan ='" + intMonth.ToString() + "'>Tháng " + tbl.MonthBook.ToString() + " năm " + tbl.YearBook.ToString() + "</td>");
            }

            Response.Write("</tr>");
            Response.Write("<tr>");
            Response.Write("<td colspan='17'></td>");

            foreach (tblListMonth tbl in lstMonth)
            {
                int intMonth = DateTime.DaysInMonth(tbl.YearBook, tbl.MonthBook);
                for (int i = 1; i <= intMonth; i++)
                    Response.Write("<td>" + i.ToString() + "</td>");
            }

            Response.Write("</tr>");
            double intSTT = 1;
            double dbCpm = 0;
            double dbReach = 0;
            foreach (tblExcel obj in campaignRepository.PrintCampaign(Id))
            {
                dbReach = obj.DanSo.Value * 70 / 100;

                Response.Write("<tr>");
                Response.Write("<td>" + intSTT.ToString() + "</td>");
                Response.Write("<td>" + obj.AreaName + "</td>");
                Response.Write("<td>" + obj.ProvinceName + "</td>");
                Response.Write("<td>" + obj.DistrictName + "</td>");
                Response.Write("<td>" + obj.SoXa + "</td>");
                Response.Write("<td>" + obj.DanSo + "</td>");
                Response.Write("<td>" + obj.SoLan + "</td>");
                Response.Write("<td>" + obj.SoLan * obj.DanSo + "</td>");
                Response.Write("<td>" + dbReach + "</td>");

                dbCpm = (obj.DonGia.Value / dbReach * 1000) / 21000;
                Response.Write("<td>" + String.Format("{0:0.00}", dbCpm) + "</td>");
                List<string> lst = new List<string>() { "", "", "" };

                intSTT++;

                if (obj.SoXa != null)
                    intSoXa += obj.SoXa.Value;

                if (obj.DanSo != null)
                    intDanSo += obj.DanSo.Value;

                if (obj.SoLan != null)
                    intTanSuat += obj.SoLan.Value;

                if (obj.SoLan != null && obj.DanSo != null)
                    intTongLuotNghe += obj.SoLan.Value * obj.DanSo.Value;

                intDoReach += dbReach;
                intTongDonGia += obj.DonGia.Value;

                foreach (tblBroadCast oBroad in stationRepository.tblStationGetBroadCasttime(Id, obj.StationId.Value).ToList())
                {
                    switch (oBroad.SectionId.ToString())
                    {
                        case "1":
                            lst[0] = oBroad.BroadCastTime;
                            break;
                        case "3":
                            lst[1] = oBroad.BroadCastTime;
                            break;
                        case "4":
                            lst[2] = oBroad.BroadCastTime;
                            break;
                    }
                }

                Response.Write("<td>" + lst[0] + "</td>");
                Response.Write("<td>" + lst[1] + "</td>");
                Response.Write("<td>" + lst[2] + "</td>");
                Response.Write("<td>" + obj.DonGia + "</td>");
                Response.Write("<td>" + obj.SoNgay + "</td>");
                Response.Write("<td>" + obj.ChietKhau + "</td>");
                Response.Write("<td>" + obj.DonGia * obj.SoNgay + "</td>");
                foreach (tblListMonth tbl in lstMonth)
                {
                    int intMonth = DateTime.DaysInMonth(tbl.YearBook, tbl.MonthBook);
                    string strMonth = blockingRepository.tblBlockGetListByBookingId(Id, obj.StationId.Value, tbl.MonthBook);

                    for (int i = 1; i <= intMonth; i++)
                    {
                        string strDay = string.Empty;

                        foreach (string str in strMonth.Split(','))
                        {
                            if (i.ToString() == str)
                            {
                                strDay = "x";
                                break;
                            }
                        }
                        Response.Write("<td>" + strDay + "</td>");
                    }
                }
                Response.Write("</tr>");
            }

            Response.Write("<tr>");
            Response.Write("<td colspan='4'></td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + intSoXa.ToString() + "</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + intDanSo.ToString() + "</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + intTanSuat.ToString() + "</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + intTongLuotNghe.ToString() + "</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + intDoReach.ToString() + "</td>");
            intTongCpm = (intTongDonGia / intTongLuotNghe * 1000) / 21000;
            Response.Write("<td style='color:Red; font-weight:bold'>" + String.Format("{0:0.00}", intTongCpm) + "</td>");
            Response.Write("<td colspan='3'></td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + intTongDonGia.ToString() + "</td>");
            Response.Write("</tr>");
            Response.Write("<tr></tr>");
            Response.Write("<tr></tr>");
            Response.Write("<tr>");
            Response.Write("<td colspan='4'>Ghi chú: Đơn giá trên chưa bao gồm 10% VAT</td>");
            Response.Write("</tr>");

            Response.Write("<tr></tr>");
            Response.Write("<tr></tr>");
            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td>Nội dung</td>");
            Response.Write("<td>Chỉ số</td>");
            Response.Write("<td>Tỷ lệ</td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td>Tổng số huyện/thị trên toàn quốc</td>");
            Response.Write("<td>698</td>");
            Response.Write("<td></td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>Tổng số huyện/thị trong hệ thống loa</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + intSTT.ToString() + "</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + String.Format("{0:0}", intSTT / 698 * 100) + "%</td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td>Tổng dân số</td>");
            Response.Write("<td>" + intDanSo + "</td>");
            Response.Write("<td></td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>Tổng dân số trong hệ thống loa</td>");
            Response.Write("<td style='color:Red; font-weight:bold'>" + intDoReach.ToString() + "</td>");
            Response.Write("<td></td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td>Reach (70%)</td>");
            Response.Write("<td>" + intDoReach.ToString() + "</td>");
            Response.Write("<td></td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td>Tần suất phát sóng</td>");
            Response.Write("<td>2-3 lần/ngày</td>");
            Response.Write("<td></td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td>Lượt nghe/1 ngày:</td>");
            Response.Write("<td>" + intTongLuotNghe + "</td>");
            Response.Write("<td>trung bình/1 ngày</td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write("</td>");
            Response.Write("<td>Chi phí phát sóng/1 ngày:</td>");
            Response.Write("<td>" + intTongDonGia + "</td>");
            Response.Write("<td></td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td></td>");
            Response.Write("<td rowspan='2'>Chi phí QC/1,000 lượt nghe (CPM):</td>");
            Response.Write("<td>" + String.Format("{0:0}", intTongDonGia / (intTongLuotNghe / 1000)) + "</td>");
            Response.Write("<td>(vnđ)</td>");
            Response.Write("</tr>");

            Response.Write("<tr>");
            Response.Write("<td></td>");
            Response.Write("<td>" + String.Format("{0:0.00}", intTongCpm) + "</td>");
            Response.Write("<td>(usd)</td>");
            Response.Write("</tr>");


            Response.Write("</table>");
            Response.End();
            return View();
        }
    }
}
